package com.ayf.payment.game.api.controller.player;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.dto.player.PlayerInfoApiDTO;
import com.ayf.payment.game.api.dto.player.PlayerPhoneDTO;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.SensitiveDataUtil;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.integral.dto.*;
import com.ayf.payment.integral.exception.IntegralInfoException;
import com.ayf.payment.integral.service.remote.IntegralRemoteService;
import com.ayf.payment.integral.vo.IntegralVO;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: zh-liang
 * @Date : 2020-08-20 21:16
 */
@RestController
@RequestMapping("/v/player")
public class MerchantPlayerController {

    private static final String PLATFORM_CODE = System.getenv("GAME_AYFPAY_PLATFORM_CODE");

    @Reference(version = "1.0.0",check = false)
    private IntegralRemoteService integralRemoteService;
    @Resource
    private PlayerApi playerApi;

    /**
     * 玩家积分余额列表查询
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/integralList")
    public CommonResult<MyPageDTO<IntegralInfoDTO>> integralList(MerchantDTO dto, @RequestBody IntegralVO vo) {
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            if (StrUtil.isNotBlank(vo.getPhone())) {
                if (!Validator.isMobile(vo.getPhone())) {
                    return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "玩家积分余额列表查询成功", new MyPageDTO<>());
                }
                PlayerInfoApiDTO playerInfo = playerApi.getPlayerInfo(vo.getPhone());
                if (playerInfo == null) {
                    return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "玩家积分余额列表查询成功", new MyPageDTO<>());
                }
                vo.setPlayerId(playerInfo.getId());
            }
            vo.setPlatformCode(PLATFORM_CODE);
            vo.setGmId(dto.getId());
            MyPageDTO<IntegralInfoDTO> myPageDTO = integralRemoteService.integralList(vo);
            if (CollUtil.isEmpty(myPageDTO.getRecords())) {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "玩家积分余额列表查询成功", myPageDTO);
            }
            Set<Long> idsSet = new HashSet<>();
            for (IntegralInfoDTO logDTO : myPageDTO.getRecords()) {
                idsSet.add(logDTO.getPlayerId());
            }
            List<Long> ids = new ArrayList<>(idsSet);
            List<PlayerPhoneDTO> phoneByIds = playerApi.getPhoneByIds(ids);
            for (IntegralInfoDTO logDTO : myPageDTO.getRecords()) {
                for (PlayerPhoneDTO phoneById : phoneByIds) {
                    if (logDTO.getPlayerId().equals(phoneById.getId())) {
                        logDTO.setPhone(SensitiveDataUtil.mobileEncrypt(phoneById.getPhone()));
                        break;
                    }
                }
            }
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "玩家积分余额列表查询成功", myPageDTO);
        } catch (IntegralInfoException e) {
            if (e.getCode() == 201) {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "玩家积分余额列表查询成功", new MyPageDTO<>());
            }
            if (e.getCode() == -1) {
                LogPortal.error("[{}]玩家积分余额列表查询失败，错误信息:[{}]", uniqueId, e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }

    /**
     * 积分记录查询
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/integralLogList")
    public CommonResult<MyPageDTO<IntegralLogDTO>> integralLogList(MerchantDTO dto, @RequestBody IntegralVO vo) {
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            if (StrUtil.isNotBlank(vo.getPhone())) {
                if (!Validator.isMobile(vo.getPhone())) {
                    return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "积分记录查询成功", new MyPageDTO<>());
                }
                PlayerInfoApiDTO playerInfo = playerApi.getPlayerInfo(vo.getPhone());
                if (playerInfo == null) {
                    return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "积分记录查询成功", new MyPageDTO<>());
                }
                vo.setPlayerId(playerInfo.getId());
            }
            vo.setPlatformCode(PLATFORM_CODE);
            vo.setGmId(dto.getId());
            MyPageDTO<IntegralLogDTO> myPageDTO = integralRemoteService.integralLogList(vo);
            if (CollUtil.isEmpty(myPageDTO.getRecords())) {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "积分记录查询成功", myPageDTO);
            }
            Set<Long> idsSet = new HashSet<>();
            for (IntegralLogDTO logDTO : myPageDTO.getRecords()) {
                idsSet.add(logDTO.getPlayerId());
            }
            List<Long> ids = new ArrayList<>(idsSet);
            List<PlayerPhoneDTO> phoneByIds = playerApi.getPhoneByIds(ids);
            for (IntegralLogDTO logDTO : myPageDTO.getRecords()) {
                for (PlayerPhoneDTO phoneById : phoneByIds) {
                    if (logDTO.getPlayerId().equals(phoneById.getId())) {
                        logDTO.setPhone(SensitiveDataUtil.mobileEncrypt(phoneById.getPhone()));
                        break;
                    }
                }
            }
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "积分记录查询成功", myPageDTO);
        } catch (IntegralInfoException e) {
            if (e.getCode() == 201) {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "积分记录查询成功", new MyPageDTO<>());
            }
            if (e.getCode() == -1) {
                LogPortal.error("[{}]积分记录查询失败，错误信息:[{}]", uniqueId, e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }

    /**
     * 兑换订单查询
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/playerOrderList")
    public CommonResult<MyPageDTO<IntegralExchangeOrderDTO>> playerOrderList(MerchantDTO dto, @RequestBody IntegralVO vo) {
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            if (StrUtil.isNotBlank(vo.getPhone())) {
                if (!Validator.isMobile(vo.getPhone())) {
                    return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "兑换订单列表查询成功", new MyPageDTO<>());
                }
                PlayerInfoApiDTO playerInfo = playerApi.getPlayerInfo(vo.getPhone());
                if (playerInfo == null) {
                    return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "兑换订单列表查询成功", new MyPageDTO<>());
                }
                vo.setPlayerId(playerInfo.getId());
            }
            vo.setPlatformCode(PLATFORM_CODE);
            vo.setGmId(dto.getId());
            MyPageDTO<IntegralExchangeOrderDTO> myPageDTO = integralRemoteService.integralOrderList(vo);
            if (CollUtil.isEmpty(myPageDTO.getRecords())) {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "兑换订单查询成功", myPageDTO);
            }
            Set<Long> idsSet = new HashSet<>();
            for (IntegralExchangeOrderDTO logDTO : myPageDTO.getRecords()) {
                idsSet.add(logDTO.getPlayerId());
            }
            List<Long> ids = new ArrayList<>(idsSet);
            List<PlayerPhoneDTO> phoneByIds = playerApi.getPhoneByIds(ids);
            for (IntegralExchangeOrderDTO logDTO : myPageDTO.getRecords()) {
                for (PlayerPhoneDTO phoneById : phoneByIds) {
                    if (logDTO.getPlayerId().equals(phoneById.getId())) {
                        logDTO.setPhone(SensitiveDataUtil.mobileEncrypt(phoneById.getPhone()));
                        break;
                    }
                }
            }
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "兑换订单查询成功", myPageDTO);
        } catch (IntegralInfoException e) {
            if (e.getCode() == -1) {
                LogPortal.error("[{}]兑换订单查询失败，错误信息:[{}]", uniqueId, e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }

    /**
     * 确认兑换
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/confirm")
    public CommonResult<?> confirm(MerchantDTO dto, @RequestBody IntegralVO vo) {
        if (StrUtil.isEmpty(vo.getExchangeOrderId())) {
            throw new ParameterException("兑换订单id不能为空");
        }
        if (vo.getStatus() == null) {
            throw new ParameterException("状态不能为空");
        }
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            vo.setPlatformCode(PLATFORM_CODE);
            vo.setGmId(dto.getId());
            if (integralRemoteService.confirmOrder(vo)) {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "操作成功");
            }
        } catch (IntegralInfoException e) {
            if (e.getCode() == -1) {
                LogPortal.error("[{}]兑换订单查询失败，错误信息:[{}]", uniqueId, e.getMsg());
            } else if (e.getCode() == -5) {
                throw new ParameterException(e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }

    /**
     * 变更玩家积分
     */
    @RequestMapping(method = RequestMethod.POST, value = "/changeIntegral")
    public CommonResult<?> changeIntegral(MerchantDTO dto, @RequestBody IntegralDTO vo) {
        if (vo.getPlayerId() == null) {
            throw new ParameterException("playerId不能为空");
        }
        if (vo.getVal() == null) {
            throw new ParameterException("积分不能为空");
        }
        if (vo.getVal() <= 0) {
            throw new ParameterException("变更的积分必须大于0");
        }
        if (StrUtil.isEmpty(vo.getRemark())) {
            throw new ParameterException("原因不能为空");
        }
        if (vo.getType() == null) {
            throw new ParameterException("变更类型不能为空");
        }
        if (vo.getType() != 3 && vo.getType() != 4) {
            throw new ParameterException("变更类型错误");
        }
        vo.setPlatformCode(PLATFORM_CODE);
        vo.setGmId(dto.getId());
        if (vo.getType() == 4) {
            IntegralInfoDTO integralInfo = integralRemoteService.getIntegralInfo(vo);
            if (integralInfo.getVal() - vo.getVal() < 0) {
                throw new ParameterException("减少的积分不能大于玩家当前积分");
            }
        }
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            integralRemoteService.changeIntegral(vo);
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "变更成功");
        } catch (IntegralInfoException e) {
            if (e.getCode() == -1) {
                LogPortal.error("[{}]变更玩家[{}]积分失败，错误信息:[{}]", uniqueId, vo.getPlayerId(), e.getMsg());
            } else if (e.getCode() == -5) {
                throw new ParameterException(e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }

}
